#include "wifi-http.h"
#include "st7735.h"
#include "esp_log.h"
#include "esp_http_client.h"
#include "string.h"
#include "stdlib.h"

bool wifi_connected = false;
bool http_request_failed=false;

static const char *TAG = "WIFI_HTTP";

// Wi-Fi 配置
#define WIFI_SSID CONFIG_MY_WIFI_SSID
#define WIFI_PASS CONFIG_MY_WIFI_PASSWORD

// 事件处理函数
static void wifi_event_handler(void* arg, esp_event_base_t event_base,
                               int32_t event_id, void* event_data) {
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
        esp_wifi_connect();
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
        ESP_LOGI(TAG, "Got IP: " IPSTR, IP2STR(&event->ip_info.ip));
        wifi_connected = true;
    }
}

void wifi_init() {
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_create_default_wifi_sta();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL));
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL));

    wifi_config_t wifi_config;
    bzero(&wifi_config, sizeof(wifi_config));
    strcpy((char *)wifi_config.sta.ssid, WIFI_SSID);
    strcpy((char *)wifi_config.sta.password, WIFI_PASS);

    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
    ESP_ERROR_CHECK(esp_wifi_start());
    ESP_LOGI(TAG, "Wi-Fi started");
}

#define JPG_BUFFER_SIZE 37*1024
uint8_t jpg_data[JPG_BUFFER_SIZE];
// uint8_t *jpg_data=NULL;
size_t jpg_size=0;

esp_err_t http_event_handler(esp_http_client_event_t *evt) {
    switch(evt->event_id) {
        case HTTP_EVENT_ERROR:
            ESP_LOGD(TAG, "HTTP_EVENT_ERROR");
            break;
        case HTTP_EVENT_ON_DATA:
            /* 
            // dynamic version, not working because big JPG file
            if (!esp_http_client_is_chunked_response(evt->client)) {
                // If user_data buffer is configured, copy the response into the buffer
                if (jpg_data == NULL) {
                    jpg_data = (uint8_t *) malloc(esp_http_client_get_content_length(evt->client));
                    jpg_size = 0;
                    if (jpg_data == NULL) {
                        ESP_LOGE(TAG, "Failed to allocate memory for output buffer");
                        return ESP_FAIL;
                    }
                }
                memcpy(jpg_data + jpg_size, evt->data, evt->data_len);

                jpg_size += evt->data_len;
            }*/
            if(jpg_size+evt->data_len > JPG_BUFFER_SIZE) break;
            memcpy(jpg_data+jpg_size,evt->data, evt->data_len);
            jpg_size += evt->data_len;
            break;
        case HTTP_EVENT_ON_FINISH:{
            // 获取 HTTP 状态码
            int status_code = esp_http_client_get_status_code(evt->client);
            if (status_code == 404) {
                ESP_LOGE(TAG, "HTTP Error: 404 - File not found");
                // free(jpg_data);
                // jpg_data = NULL;
                jpg_size = 0;
                http_request_failed=true;
                return ESP_FAIL; // 返回失败
            }
            if (status_code >= 200 && status_code < 300) {
                http_request_failed=false;
                ESP_LOGI(TAG, "JPG size: %d bytes", jpg_size);
                decode_jpeg_to_rgb565(jpg_data, jpg_size);
                // free(jpg_data);
                // jpg_data = NULL;
                jpg_size=0;
            } else {
                ESP_LOGE(TAG, "HTTP request failed with status code: %d", status_code);
                // free(jpg_data);
                // jpg_data = NULL;
                jpg_size = 0;
                http_request_failed=true;
                return ESP_FAIL;
            }
            break;
            }
        default:
            break;
    }
    return ESP_OK;
}

